package bjtu.tjj.simpledy.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

public class FileUtils {
    public final static String[] VIDEO_SUFFIXES = {"mp4", "webm", "ogg"};
    public final static String[] IMAGE_SUFFIXES = {"jpg", "png", "webp"};
    public final static File ROOT_DIR;

    static {
        ROOT_DIR = new File("file");
        if (!ROOT_DIR.exists() && !ROOT_DIR.mkdir()) {
            throw new RuntimeException("file根目录创建失败");
        }
    }

    public static String getSuffix(MultipartFile file) {
        String filename = file.getOriginalFilename();
        return getSuffix(filename);
    }

    public static String getSuffix(String filename) {
        if (filename == null) {
            return null;
        }
        int idx = filename.lastIndexOf('.');
        if (idx == -1 || idx == filename.length() - 1) {
            return null;
        }
        return filename.substring(idx + 1);
    }

    public static boolean isVideo(String suffix) {
        for (String s : VIDEO_SUFFIXES) {
            if (s.equals(suffix)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isImage(String suffix) {
        for (String s : IMAGE_SUFFIXES) {
            if (s.equals(suffix)) {
                return true;
            }
        }
        return false;
    }

    public static File saveFile(byte[] bytes, String suffix) throws IOException {
        String filename = "%s.%s".formatted(
                SHA256Utils.encode(bytes),
                suffix
        );
        File file = new File(ROOT_DIR, filename);
        if (!file.exists()) {
            org.apache.commons.io.FileUtils.writeByteArrayToFile(file, bytes);
        }
        return file;
    }
}
